#!/bin/bash

FILE="$HOME/.docker/daemon.json"
MIRROR="https:\/\/mirror.gcr.io"

if [ ! -f "$FILE" ]; then
  echo -e "{\n  \"registry-mirrors\": [\n    \"$MIRROR\"\n  ]\n}" > $FILE
else
  if ! grep -q "registry-mirrors" $FILE; then
    sed -i.bak 's/}/, "registry-mirrors": ["'$MIRROR'"] }/' $FILE
  else
    MIRROR_ESCAPED=$(echo "$MIRROR" | sed 's/\//\\\//g')
    if grep -q "$MIRROR_ESCAPED" $FILE; then
      echo "$MIRROR is already in the registry-mirrors list."
    else
      sed -i.bak '/registry-mirrors/ a\'$'\n''    "'$MIRROR'",' $FILE
    fi
  fi
fi